package com.cm386.final_project_timezonealert.model;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import com.cm386.final_project_timezonealert.view.SelectedCityItem;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class WeatherService {


	public static Weather getCurrentWeatherByCityName(String cityName, Bitmap defaultWeathIcon, String defaultTemperature, SelectedCityItem selectedCityItem){
		Weather weather = new Weather();
		weather.setWeatherIcon(defaultWeathIcon);
		weather.setTemperature(defaultTemperature);
		weather.setDayNightLabel(Weather.DEFAULT_DAY_NIGHT_LABEL);
				
		HttpClient httpClient = new DefaultHttpClient();
		final HttpParams httpParams = httpClient.getParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, 1000 * 30);
		HttpConnectionParams.setSoTimeout(httpParams, 1000 * 30);
		ConnManagerParams.setTimeout(httpParams, 1000 * 30);
		
		Integer selectHour = Integer.valueOf(selectedCityItem.getHour());
		Integer selectMinutes = Integer.valueOf(selectedCityItem.getMinutes());
		
		
		try {
			String url = "http://api.openweathermap.org/data/2.5/weather?q=" + URLEncoder.encode(cityName, "UTF-8");

			HttpGet get = new HttpGet(url);
			HttpResponse resp = httpClient.execute(get);
			String respString = EntityUtils.toString(resp.getEntity());

			if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				JSONObject json = new JSONObject(respString);
				if (json!=null) {
					
					JSONObject mainObj = json.getJSONObject("main");
					if (mainObj!=null) {
						weather.setTemperature(String.valueOf((int)(mainObj.getDouble("temp")-273.15))+"º");
						weather.setMinTemperature(String.valueOf((int)(mainObj.getDouble("temp_min")-273.15))+"º");
						weather.setMaxTemperature(String.valueOf((int)(mainObj.getDouble("temp_max")-273.15))+"º");
					}
					
					
					JSONObject sysObj = json.getJSONObject("sys");
					if (sysObj!=null) {
						weather.setCountry(sysObj.getString("country"));
						weather.setSunRise(new Date((sysObj.getLong("sunrise")*1000)));
						weather.setSunSet(new Date((sysObj.getLong("sunset")*1000)));
						
						
						Calendar sunRise = Calendar.getInstance(TimeZone.getTimeZone(selectedCityItem.getTimeZone()), Locale.getDefault());
						sunRise.setTime(weather.getSunRise());	
						int sunRiseHour = sunRise.get(Calendar.HOUR_OF_DAY);
						int sunRiseMinutes = sunRise.get(Calendar.MINUTE);
						
						Calendar sunSet = Calendar.getInstance(TimeZone.getTimeZone(selectedCityItem.getTimeZone()), Locale.getDefault());
						sunSet.setTime(weather.getSunSet());
						int sunSetHour = sunSet.get(Calendar.HOUR_OF_DAY);
						int sunSetMinutes = sunSet.get(Calendar.MINUTE);
						
						if (
								(selectHour==sunRiseHour && selectMinutes>=sunRiseMinutes)
								||
								(selectHour==sunSetHour && selectMinutes<sunSetMinutes)
								||
								(selectHour>sunRiseHour && selectHour<sunSetHour)
							)
							weather.setDayNightLabel(Weather.DAY_LABEL);						
						else
							weather.setDayNightLabel(Weather.NIGHT_LABEL);
						
					}
					
					weather.setCityId(json.getInt("id"));
					weather.setCityName(json.getString("name"));
					weather.setLastUpdateTime(new Date(json.getLong("dt")*1000));
					
					
					// We get weather info (This is an array)
					JSONArray jArr = json.getJSONArray("weather");
					
					if (jArr!=null) {
						// We use only the first value
						JSONObject jWeather = jArr.getJSONObject(0);
						if (jWeather!=null) {
							weather.setMain(jWeather.getString("main"));
							weather.setDescription(jWeather.getString("description"));
							weather.setIconUrl("http://openweathermap.org/img/w/" + jWeather.getString("icon") + ".png");
							weather.setWeatherIcon(getBitmapByUrl(weather.getIconUrl()));
							
							if (jWeather.getString("icon").endsWith("d") || jWeather.getString("icon").endsWith("D"))
								weather.setDayNightLabel(Weather.DAY_LABEL);
							else if (jWeather.getString("icon").endsWith("n") || jWeather.getString("icon").endsWith("N"))
								weather.setDayNightLabel(Weather.NIGHT_LABEL);
							else
								weather.setDayNightLabel(null);
						}
					}
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		

		return weather;
	}
	public static Weather getWeatherBySelectedDateTimeAndCityName(String cityName, Date selectedDateTime) {
		//Weather weather = WeatherService.getCurrentWeatherByCityName(cityName);
		Weather weather = new Weather();
		
		HttpClient httpClient = new DefaultHttpClient();
		final HttpParams httpParams = httpClient.getParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, 1000 * 30);
		HttpConnectionParams.setSoTimeout(httpParams, 1000 * 30);
		ConnManagerParams.setTimeout(httpParams, 1000 * 30);
		
		
		try {
			String url = "http://api.openweathermap.org/data/2.5/forecast?q=" + URLEncoder.encode(cityName, "UTF-8");

			HttpGet get = new HttpGet(url);
			HttpResponse resp = httpClient.execute(get);
			String respString = EntityUtils.toString(resp.getEntity());

			if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				JSONObject json = new JSONObject(respString);
				if (json!=null) {
					// We get forecast info (This is an array)
					JSONArray jArr = json.getJSONArray("list");
					
					if (jArr!=null) {
						for (int i=0; i<jArr.length(); i++) {
							JSONObject jForecast = jArr.getJSONObject(i);
							if (jForecast!=null) {
								if (selectedDateTime.getTime()/1000 <= jForecast.getLong("dt")) {
									
									JSONObject mainObj = jForecast.getJSONObject("main");
									if (mainObj!=null) {
										weather.setTemperature(String.valueOf((int)(mainObj.getDouble("temp")-273.15))+"º");
										weather.setMinTemperature(String.valueOf((int)(mainObj.getDouble("temp_min")-273.15))+"º");
										weather.setMaxTemperature(String.valueOf((int)(mainObj.getDouble("temp_max")-273.15))+"º");
									}
									
									// We get weather info (This is an array)
									JSONArray wArr = jForecast.getJSONArray("weather");									
									if (wArr!=null) {
										// We use only the first value
										JSONObject jWeather = wArr.getJSONObject(0);
										if (jWeather!=null) {
											weather.setMain(jWeather.getString("main"));
											weather.setDescription(jWeather.getString("description"));
											weather.setIconUrl("http://openweathermap.org/img/w/" + jWeather.getString("icon") + ".png");
											weather.setWeatherIcon(getBitmapByUrl(weather.getIconUrl()));
										}
									}
									
									break;
								}
							}
							
						}

					}
					
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		

		return weather;
		
	}
	

	
	private static Bitmap getBitmapByUrl(String iconUrl) {
		 Bitmap mBitmap = null;  
	        try {  
	            URL url = new URL(iconUrl);  
	            HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
	            InputStream is = conn.getInputStream();  
	            mBitmap = BitmapFactory.decodeStream(is);  
	              
	        } catch (MalformedURLException e) {  
	            e.printStackTrace();  
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        }  
	        
	        return mBitmap;  
	    }  
	
	

}
